<template>
  <div class="profile-view">
    <div class="profile-container">
      <!-- 头部区域 -->
      <div class="profile-header">
        <el-button class="header-back" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h1 class="profile-title">个人资料</h1>
        <p class="profile-subtitle">管理您的账户信息</p>
      </div>
      
      <!-- 主要内容区域 -->
      <div class="profile-content">
        <!-- 头像和等级信息并排显示 -->
        <div class="avatar-level-section">
          <!-- 头像区域 -->
          <div class="avatar-section">
            <div class="avatar-container">
              <el-avatar 
                :size="120" 
                :src="renderAvatarUrl || defaultAvatar"
                class="user-avatar"
              />
              <div class="avatar-overlay" @click="triggerFileUpload">
                <el-icon class="upload-icon"><Camera /></el-icon>
                <span class="upload-text">更换头像</span>
              </div>
            </div>
            <input 
              ref="fileInput" 
              type="file" 
              accept="image/*" 
              style="display: none" 
              @change="handleAvatarUpload"
            />
          </div>

          <!-- 等级信息显示 -->
          <div class="level-info-section" v-if="levelInfo || levelLoading">
            <div class="info-card level-card">
              <div v-if="levelLoading" class="loading-state">
                <el-icon class="loading-icon"><Loading /></el-icon>
                <span>正在加载等级信息...</span>
              </div>
              <div v-else-if="levelInfo" class="level-content">
                <div class="level-header">
                  <span class="level-badge">LV.{{ levelInfo.currentLevel ?? 0 }}</span>
                  <span class="title-separator" v-if="levelInfo.currentTitle">·</span>
                  <TitleBadge 
                    v-if="levelInfo.currentTitle"
                    :title="levelInfo.currentTitle"
                    :level="levelInfo.currentLevel"
                    size="md"
                    :active="true"
                  />
                </div>
                <div class="level-progress">
                  <el-progress :percentage="levelPercent" :stroke-width="8" />
                  <div class="exp-text">{{ levelInfo.currentExperience }} / {{ levelInfo.experienceRequiredForNextLevel }} 经验</div>
                </div>
              </div>
              <div v-else class="error-state">
                <el-icon class="error-icon"><Warning /></el-icon>
                <span>等级信息加载失败</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 基本信息显示 -->
        <div class="basic-info-section">
          <div class="info-card">
            <div class="info-item">
              <el-icon class="info-icon"><User /></el-icon>
              <div class="info-content">
                <span class="info-label">用户名</span>
                <span class="info-value">{{ userStore.user?.userName || '未设置' }}</span>
              </div>
            </div>
            <div class="info-item">
              <el-icon class="info-icon"><Message /></el-icon>
              <div class="info-content">
                <span class="info-label">邮箱地址</span>
                <span class="info-value">{{ userStore.user?.email || '未设置' }}</span>
              </div>
            </div>
            <div class="info-item">
              <el-icon class="info-icon"><Phone /></el-icon>
              <div class="info-content">
                <span class="info-label">手机号码</span>
                <span class="info-value">{{ userStore.user?.phoneNumber || '未设置' }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 称号管理已删除 -->
        
        <!-- 所有称号展示 -->
        <div class="all-titles-section" v-if="allTitles && allTitles.length > 0">
          <AllTitlesDisplay 
            :all-titles="allTitles"
            :user-titles="userTitles"
            :current-title="levelInfo?.currentTitle || ''"
            @title-changed="handleTitleChange"
          />
        </div>
        
        <!-- 游戏历史记录 -->
        <div class="game-history-section">
          <div class="section-header">
            <h3 class="section-title">
              <el-icon class="title-icon"><Trophy /></el-icon>
              游戏历史记录
            </h3>
            <div class="section-actions">
              <el-select v-model="historyFilter" placeholder="筛选类型" size="small" style="width: 120px">
                <el-option label="全部" value="all" />
                <el-option label="胜利" value="win" />
                <el-option label="失败" value="lose" />
                <el-option label="平局" value="draw" />
              </el-select>
              <el-button @click="refreshGameHistory" :loading="historyLoading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
          
          <!-- 游戏统计概览 -->
          <div class="game-stats-overview" v-if="gameStats">
            <div class="stat-card">
              <div class="stat-icon">🎮</div>
              <div class="stat-content">
                <div class="stat-value">{{ gameStats.totalGames }}</div>
                <div class="stat-label">总游戏数</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">🏆</div>
              <div class="stat-content">
                <div class="stat-value">{{ gameStats.totalWins }}</div>
                <div class="stat-label">胜利次数</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">📊</div>
              <div class="stat-content">
                <div class="stat-value">{{ gameStats.winRate }}%</div>
                <div class="stat-label">胜率</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">🎨</div>
              <div class="stat-content">
                <div class="stat-value">{{ gameStats.totalAreaPainted }}</div>
                <div class="stat-label">总涂色面积</div>
              </div>
            </div>
          </div>
          
          <!-- 游戏历史列表 -->
          <div class="game-history-list" v-if="gameHistory.length > 0">
            <div class="history-item" v-for="game in gameHistory" :key="game.id">
              <div class="game-info">
                <div class="game-header">
                  <span class="game-date">{{ formatGameDate(game.createdAt) }}</span>
                  <span :class="['game-result', getGameResultClass(game.result)]">
                    {{ getGameResultText(game.result) }}
                  </span>
                </div>
                <div class="game-details">
                  <span class="room-name">房间: {{ game.roomName || '未知房间' }}</span>
                  <span class="game-duration">时长: {{ formatGameDuration(game.duration) }}</span>
                  <span class="player-count">玩家: {{ game.playerCount || 0 }}人</span>
                </div>
                <div class="game-stats">
                  <span class="area-painted">涂色面积: {{ game.areaPainted || 0 }} 像素</span>
                  <span class="final-rank">最终排名: {{ game.finalRank || '未知' }}</span>
                </div>
              </div>
              <div class="game-actions">
                <el-button 
                  size="small" 
                  @click="viewGameDetail(game.id)"
                  :disabled="!game.id"
                >
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
          
          <!-- 空状态 -->
          <div v-else-if="!historyLoading" class="empty-history">
            <el-empty description="暂无游戏记录" :image-size="100">
            </el-empty>
          </div>
          
          <!-- 加载状态 -->
          <div v-if="historyLoading" class="loading-history">
            <el-skeleton :rows="3" animated />
          </div>
          
          <!-- 分页 -->
          <div class="pagination-wrapper" v-if="totalPages > 1">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50]"
              :total="totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handlePageSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
        

        


        <!-- 操作按钮区域 -->
        <div class="actions-section">
          <el-button type="primary" @click="showEditDialog = true" class="action-btn">
            <el-icon><Edit /></el-icon>
            编辑资料
          </el-button>
          <el-button type="warning" @click="showPasswordDialog = true" class="action-btn">
            <el-icon><Key /></el-icon>
            修改密码
          </el-button>
          <el-button type="danger" @click="handleLogout" class="action-btn">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
        
        <!-- 测试组件已删除 -->
      </div>
    </div>

    <!-- 编辑资料弹窗 -->
    <el-dialog 
      v-model="showEditDialog" 
      title="编辑个人资料" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="profileForm" 
        :rules="profileRules" 
        ref="profileFormRef" 
        label-position="top"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input 
            v-model="profileForm.userName" 
            placeholder="请输入用户名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input 
            v-model="profileForm.email" 
            placeholder="请输入邮箱地址"
            :prefix-icon="Message"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input 
            v-model="profileForm.phoneNumber" 
            placeholder="请输入手机号码"
            :prefix-icon="Phone"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateProfile" :loading="userStore.loading">
            <el-icon v-if="!userStore.loading"><Check /></el-icon>
            {{ userStore.loading ? '保存中...' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog 
      v-model="showPasswordDialog" 
      title="修改密码" 
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="passwordForm" 
        :rules="passwordRules" 
        ref="passwordFormRef" 
        label-position="top"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password"
            placeholder="请输入当前密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password"
            placeholder="请输入新密码"
            :prefix-icon="Key"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password"
            placeholder="请再次输入新密码"
            :prefix-icon="Key"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="warning" @click="handleChangePassword" :loading="passwordLoading">
            <el-icon v-if="!passwordLoading"><Key /></el-icon>
            {{ passwordLoading ? '修改中...' : '修改密码' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  Message, 
  Phone, 
  Check, 
  Lock, 
  Key, 
  Camera, 
  ArrowLeft, 
  SwitchButton,
  Edit,
  Loading,
  Warning,
  Trophy,
  Refresh
} from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { http, handleApiResponse } from '@/utils/request.js'
import { userLevelAPI } from '@/api'
import { gameAPI } from '@/api'
// 测试组件已删除
import AllTitlesDisplay from '../components/user/AllTitlesDisplay.vue'
import TitleBadge from '../components/user/TitleBadge.vue'
// 使用 userLevelAPI 中的方法，不需要单独导入
const router = useRouter()
const userStore = useUserStore()

// 默认头像
const defaultAvatar = 'https://api.dicebear.com/7.x/avataaars/svg?seed=default'

// 渲染用头像URL（可能是blob URL）
const renderAvatarUrl = ref('')
let objectUrl = ''

// 通过受保护接口加载头像文件并生成URL
const loadAvatarUrl = async () => {
  try {
    const fileName = userStore.user?.avatar
    if (!fileName) {
      renderAvatarUrl.value = ''
      return
    }
    if (typeof fileName === 'string' && (fileName.startsWith('http://') || fileName.startsWith('https://'))) {
      renderAvatarUrl.value = fileName
      return
    }
    // 预览头像文件：GET /api/users/avatar-file/{fileName}
    const blob = await http.get(
      `/users/avatar-file/${fileName}`,
      {},
      { responseType: 'blob', silent: true, silentCodes: [404] }
    )
    if (objectUrl) URL.revokeObjectURL(objectUrl)
    objectUrl = URL.createObjectURL(blob)
    renderAvatarUrl.value = objectUrl
  } catch (e) {
    console.error('加载头像失败，将使用默认头像', e)
    renderAvatarUrl.value = ''
  }
}

// 文件输入引用
const fileInput = ref()

// 表单引用
const profileFormRef = ref()
const passwordFormRef = ref()

// 弹窗显示状态
const showEditDialog = ref(false)
const showPasswordDialog = ref(false)

// 加载状态
const passwordLoading = ref(false)

// 个人资料表单
const profileForm = reactive({
  userName: '',
  email: '',
  phoneNumber: ''
})

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 等级信息
const levelInfo = ref(null)
const levelLoading = ref(false)

// 称号信息
const allTitles = ref([])
const userTitles = ref([])

// 游戏历史记录
const gameHistory = ref([])
const historyLoading = ref(false)
const historyFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const totalPages = ref(0)
const gameStats = ref(null)

// 调试器已删除

// 简单 JWT 解码
const decodeJwt = (token) => {
  try {
    const payload = token.split('.')[1]
    const json = decodeURIComponent(atob(payload.replace(/-/g, '+').replace(/_/g, '/')).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''))
    return JSON.parse(json)
  } catch { return null }
}

const loadLevelInfo = async () => {
  try {
    if (!userStore.isAuthenticated) return
    let uid = userStore.user?.id
    if (!uid) {
      const tokenStr = localStorage.getItem('token')
      const tokenObj = tokenStr ? (()=>{ try{return JSON.parse(tokenStr)}catch{return null} })() : null
      const accessToken = tokenObj?.accessToken
      const payload = accessToken ? decodeJwt(accessToken) : null
      uid = payload?.uid || payload?.user_id || payload?.userId || payload?.sub
    }
    if (!uid) return
    levelLoading.value = true
    
    // 第一步：先获取所有可用称号
    try {
      const allTitlesRes = await userLevelAPI.getAllTitles({ meta: { silent: true } })
      allTitles.value = handleApiResponse(allTitlesRes, 'data') || []
      console.log('所有称号加载成功:', allTitles.value)
    } catch (error) {
      console.error('获取所有称号失败:', error)
      allTitles.value = []
    }
    
    // 第二步：获取用户等级信息
    try {
      const levelRes = await userLevelAPI.getUserLevel(uid, { meta: { silent: true } })
      const levelData = handleApiResponse(levelRes, 'data')
      
      // 映射用户等级数据
      levelInfo.value = {
        currentLevel: levelData?.currentLevel || 0,
        currentExperience: levelData?.currentExperience || 0,
        experienceRequiredForNextLevel: levelData?.experienceRequiredForNextLevel || 300,
        levelProgress: levelData?.levelProgress || 0,
        currentTitle: levelData?.currentTitle || '',
        totalExperience: levelData?.totalExperience || 0
      }
      
      // 从等级数据中提取已解锁称号
      if (levelData?.unlockedTitles && Array.isArray(levelData.unlockedTitles)) {
        userTitles.value = levelData.unlockedTitles.map(titleName => ({
          title: titleName,
          isUnlocked: true
        }))
      } else {
        userTitles.value = []
      }
      
      console.log('用户等级加载成功:', levelInfo.value)
      console.log('已解锁称号:', userTitles.value)
    } catch (error) {
      console.error('获取用户等级失败:', error)
      levelInfo.value = null
      userTitles.value = []
    }
    
  } catch (e) {
    console.error('加载等级信息失败:', e)
  } finally {
    levelLoading.value = false
  }
}

const levelPercent = computed(() => {
  const info = levelInfo.value
  if (!info) return 0
  if (typeof info.levelProgress === 'number') {
    const v = info.levelProgress
    if (v > 1) return Math.min(100, Math.round(v))
    return Math.round(v * 100)
  }
  if (info.experienceRequiredForNextLevel > 0) {
    return Math.round((info.currentExperience / info.experienceRequiredForNextLevel) * 100)
  }
  return 0
})

// 监听头像文件名变化，自动加载
watch(() => userStore.user?.avatar, () => {
  loadAvatarUrl()
})

// 触发文件上传
const triggerFileUpload = () => {
  fileInput.value.click()
}

// 处理头像上传
const handleAvatarUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  try {
    await userStore.uploadAvatar(userStore.user?.id, file)
    // 上传成功后刷新用户信息并加载头像
    if (userStore.user?.id) {
      await userStore.fetchUserInfo(userStore.user.id)
      await loadAvatarUrl()
    }
    ElMessage.success('头像上传成功！')
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('头像上传失败，请重试')
  }
}

// 处理更新个人资料
const handleUpdateProfile = async () => {
  try {
    await profileFormRef.value.validate()
    
    const userData = {
      userName: profileForm.userName,
      email: profileForm.email,
      phoneNumber: profileForm.phoneNumber
    }
    
    await userStore.updateUserInfo(userStore.user?.id, userData)
    
    showEditDialog.value = false
    ElMessage.success('个人资料更新成功！')
  } catch (error) {
    console.error('更新个人资料失败:', error)
    ElMessage.error('更新失败，请重试')
  }
}

// 处理修改密码
const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    const passwordData = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    }
    
    await userStore.changePassword(userStore.user?.id, passwordData)
    
    // 清空表单
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
    
    showPasswordDialog.value = false
    ElMessage.success('密码修改成功！')
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改失败，请重试')
  }
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '确认退出',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userStore.logout()
    router.push('/login')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出登录失败:', error)
    }
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 跳转到称号管理页面已删除

// 处理称号更换
const handleTitleChange = async (newTitle) => {
  try {
    if (!userStore.isAuthenticated || !userStore.user?.id) {
      ElMessage.error('用户未登录，无法更换称号')
      return
    }
    
    console.log('开始更换称号:', {
      userId: userStore.user.id,
      newTitle: newTitle.title
    })
    
    // 调用更换称号API
    const response = await userLevelAPI.changeTitle({
      userId: userStore.user.id,
      newTitle: newTitle.title
    })
    
    console.log('API响应:', response)
    
    if (response && response.code === 200) {
      ElMessage.success(`称号更换成功！当前称号：${newTitle.title}`)
      
      // 更新本地状态，不重新加载数据
      if (levelInfo.value) {
        levelInfo.value.currentTitle = newTitle.title
      }
      
      console.log('本地状态已更新，称号更换完成')
    } else {
      console.error('API返回错误:', response)
      const errorMsg = response?.message || response?.msg || '称号更换失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    console.error('更换称号失败:', error)
    
    // 尝试从错误对象中提取更详细的错误信息
    let errorMessage = '称号更换失败，请重试'
    
    if (error.response) {
      // 服务器响应了错误状态码
      const { status, data } = error.response
      errorMessage = data?.message || data?.msg || `请求失败 (${status})`
    } else if (error.request) {
      // 请求已发出但没有收到响应
      errorMessage = '网络请求失败，请检查网络连接'
    } else if (error.message) {
      // 其他错误
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  }
}

// 格式化游戏日期
const formatGameDate = (dateString) => {
  if (!dateString) return '未知'
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return '未知'
  }
}

// 格式化游戏时长
const formatGameDuration = (duration) => {
  if (duration === null || duration === undefined) return '未知'
  const minutes = Math.floor(duration / 60000)
  const seconds = Math.floor((duration % 60000) / 1000)
  return `${minutes}分${seconds}秒`
}

// 获取游戏结果文本
const getGameResultText = (result) => {
  if (result === 'win') return '胜利'
  if (result === 'lose') return '失败'
  if (result === 'draw') return '平局'
  return '未知'
}

// 获取游戏结果类名
const getGameResultClass = (result) => {
  if (result === 'win') return 'game-win'
  if (result === 'lose') return 'game-lose'
  if (result === 'draw') return 'game-draw'
  return ''
}



// 刷新游戏历史记录
const refreshGameHistory = async () => {
  if (!userStore.isAuthenticated || !userStore.user?.id) {
    ElMessage.error('用户未登录，无法查看游戏历史')
    return
  }
  historyLoading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 根据筛选条件添加参数
    if (historyFilter.value !== 'all') {
      params.result = historyFilter.value
    }
    
    const response = await gameAPI.getPlayerGameHistory(userStore.user.id, params)
    const raw = handleApiResponse(response, 'data')
    if (!raw) {
      gameHistory.value = []
      totalCount.value = 0
      totalPages.value = 0
      gameStats.value = null
      return
    }

    // 兼容多种返回结构：数组 或 含有 games/items/records 的分页对象
    const list = Array.isArray(raw) ? raw : (raw.games || raw.items || raw.records || [])

    // 将后端 GameRecord 字段映射为前端视图所需结构
    const uid = String(userStore.user.id)
    gameHistory.value = (list || []).map(rec => {
      const endedAt = rec.endedAt || rec.EndedAt || rec.createdAt || rec.CreatedAt
      // duration 可能是 分钟/秒/毫秒；统一转毫秒
      let durationRaw = (typeof rec.duration === 'number' ? rec.duration : (typeof rec.Duration === 'number' ? rec.Duration : 0))
      // 猜测单位：<1200 视为分钟；<100000 视为秒；否则视为毫秒
      if (durationRaw > 0 && durationRaw < 1200) {
        durationRaw = durationRaw * 60 * 1000
      } else if (durationRaw > 0 && durationRaw < 100000) {
        durationRaw = durationRaw * 1000
      }
      const results = rec.playerResults || rec.PlayerResults || []
      const me = results.find(r => String(r.playerId || r.PlayerId) === uid)
      const winnerId = String(rec.winnerId || rec.WinnerId || '')
      const result = winnerId && winnerId === uid ? 'win' : 'lose'
      return {
        id: rec.id || rec.Id,
        roomName: rec.roomName || rec.RoomName || '-',
        createdAt: endedAt, // 用结束时间作为展示时间
        duration: durationRaw, // 统一为毫秒
        playerCount: rec.playerCount || rec.PlayerCount || results.length || 0,
        areaPainted: me ? (me.areaCount || me.AreaCount || 0) : 0,
        finalRank: me ? (me.rank || me.Rank || '-') : '-',
        result
      }
    })

    totalCount.value = Array.isArray(raw) ? gameHistory.value.length : (raw.totalCount || raw.total || gameHistory.value.length)
    totalPages.value = raw.totalPages || Math.ceil(totalCount.value / pageSize.value)

    // 计算统计
    if (gameHistory.value.length > 0) {
      const totalGames = gameHistory.value.length
      const totalWins = gameHistory.value.filter(g => g.result === 'win').length
      const totalAreaPainted = gameHistory.value.reduce((sum, g) => sum + (g.areaPainted || 0), 0)
      const winRate = totalGames > 0 ? Math.round((totalWins / totalGames) * 100) : 0
      gameStats.value = { totalGames, totalWins, winRate, totalAreaPainted }
    } else {
      gameStats.value = null
    }
  } catch (error) {
    console.error('加载游戏历史失败:', error)
    gameHistory.value = []
    totalCount.value = 0
    totalPages.value = 0
    gameStats.value = null
  } finally {
    historyLoading.value = false
  }
}

// 处理页面大小变化
const handlePageSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  refreshGameHistory()
}

// 处理页码变化
const handlePageChange = (val) => {
  currentPage.value = val
  refreshGameHistory()
}

// 查看游戏详情
const viewGameDetail = (gameId) => {
  router.push({ path: '/game-detail', query: { id: gameId } })
}

// 页面加载时初始化
onMounted(async () => {
  // 初始化用户状态
  await userStore.init()
  
  // 如果没有登录，跳转到登录页
  if (!userStore.isAuthenticated) {
    router.push('/login')
    return
  }
  
  // 获取最新的用户信息
  if (userStore.user?.id) {
    try {
      await userStore.fetchUserInfo(userStore.user.id)
      await loadAvatarUrl()
      await loadLevelInfo()
      await refreshGameHistory() // 加载游戏历史记录
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  } else {
    // 即使没有 user.id 也尝试拉取等级（会在内部用JWT回退）
    await loadLevelInfo()
  }
  
  // 填充表单数据
  if (userStore.user) {
    profileForm.userName = userStore.user.userName || ''
    profileForm.email = userStore.user.email || ''
    profileForm.phoneNumber = userStore.user.phoneNumber || ''
  }
  
  // 确保称号数据已加载
  if (allTitles.value.length === 0) {
    await loadLevelInfo()
  }
  
})
</script>

<style scoped>
.profile-view {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
  box-sizing: border-box;
}

.profile-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 头部区域 */
.profile-header {
  position: relative;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  padding: 40px 30px;
  text-align: center;
  color: white;
}

.header-back {
  position: absolute;
  top: 12px;
  left: 12px;
  color: #fff;
  border-color: rgba(255,255,255,0.4);
  background: rgba(255,255,255,0.12);
}

.profile-title {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.profile-subtitle {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}

/* 主要内容区域 */
.profile-content {
  padding: 40px 30px;
}

/* 头像和等级信息并排布局 */
.avatar-level-section {
  display: flex;
  align-items: flex-start;
  gap: 30px;
  margin-bottom: 30px;
}

/* 头像区域 */
.avatar-section {
  text-align: center;
  flex-shrink: 0;
}

.avatar-container {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.user-avatar {
  border: 4px solid #f0f0f0;
  transition: all 0.3s ease;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.upload-text {
  font-size: 10px;
}

/* 基本信息区域 */
.basic-info-section {
  margin-bottom: 20px;
}

/* 等级信息区域 */
.level-info-section {
  flex: 1;
}

.level-card {
  height: fit-content;
}
.level-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: nowrap;
}

.level-badge {
  display: inline-block;
  font-weight: 800;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  color: #fff;
  background: linear-gradient(135deg, #f59e0b 0%, #ef4444 100%);
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.25);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.2);
  white-space: nowrap;
}

.title-separator {
  font-size: 16px;
  color: #6b7280;
  font-weight: 400;
  margin: 0 4px;
}

.level-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  background: linear-gradient(90deg, #06b6d4 0%, #3b82f6 50%, #8b5cf6 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.35), 0 2px 6px rgba(59, 130, 246, 0.25);
  white-space: nowrap;
}

/* 等级进度条样式 */
.level-progress {
  margin-top: 16px;
}

.level-progress .el-progress {
  margin-bottom: 12px;
}

.level-progress .el-progress__bar {
  border-radius: 10px;
}

.level-progress .el-progress__inner {
  border-radius: 10px;
  background: linear-gradient(90deg, #10b981 0%, #f59e0b 50%, #ef4444 100%);
}

.exp-text {
  font-size: 14px;
  color: #6b7280;
  text-align: center;
  font-weight: 500;
  margin-top: 8px;
}

.info-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 30px;
}

.loading-state, .error-state {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 20px;
  color: #6b7280;
}

.loading-icon {
  animation: spin 1s linear infinite;
  color: #3b82f6;
}

.error-icon {
  color: #ef4444;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.level-content {
  width: 100%;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #e8e8e8;
}

.info-item:last-child {
  border-bottom: none;
}

.info-icon {
  font-size: 20px;
  color: #1890ff;
  margin-right: 16px;
  width: 24px;
}

.info-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.info-value {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

/* 操作按钮区域 */
.actions-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
  margin-top: 20px;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  height: 48px;
  border-radius: 8px;
  font-weight: 500;
}

/* 弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.account-info-dialog {
  padding: 20px 0;
}

.account-info-dialog .info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e8e8e8;
}

.account-info-dialog .info-item:last-child {
  border-bottom: none;
}

.account-info-dialog .info-label {
  font-weight: 500;
  color: #666;
}

.account-info-dialog .info-value {
  color: #333;
}

/* 称号管理样式已删除 */

.all-titles-section {
  margin-top: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 游戏历史记录样式 */
.game-history-section {
  margin-top: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #e8e8e8;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.title-icon {
  font-size: 24px;
  color: #1890ff;
}

.section-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.game-stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 15px;
  padding: 20px 30px;
  border-bottom: 1px solid #e8e8e8;
}

.stat-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 15px 10px;
  background: #f0f9eb;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stat-icon {
  font-size: 36px;
  margin-bottom: 8px;
  color: #67c23a;
}

.stat-content .stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
}

.stat-content .stat-label {
  font-size: 12px;
  color: #999;
}

.game-history-list {
  padding: 20px 30px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.history-item:last-child {
  border-bottom: none;
}

.game-info {
  flex: 1;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.game-date {
  font-size: 14px;
  color: #666;
  font-weight: 400;
}

.game-result {
  font-size: 14px;
  font-weight: 600;
  padding: 4px 8px;
  border-radius: 6px;
  color: white;
}

.game-win {
  background-color: #67c23a;
}

.game-lose {
  background-color: #f56c6c;
}

.game-draw {
  background-color: #e6a23c;
}

.game-details {
  font-size: 13px;
  color: #999;
  margin-bottom: 8px;
}

.game-stats {
  font-size: 13px;
  color: #666;
}

.game-actions {
  flex-shrink: 0;
}

.empty-history {
  padding: 40px 30px;
  text-align: center;
}

.loading-history {
  padding: 40px 30px;
}

.pagination-wrapper {
  padding: 20px 30px;
  border-top: 1px solid #e8e8e8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-view {
    padding: 10px;
  }
  
  .profile-header {
    padding: 30px 20px;
  }
  
  .profile-content {
    padding: 30px 20px;
  }
  
  .profile-title {
    font-size: 28px;
  }
  
  .info-card {
    padding: 20px;
  }
  
  .actions-section {
    grid-template-columns: 1fr;
  }
  
  /* 在小屏幕上改为垂直布局 */
  .avatar-level-section {
    flex-direction: column;
    gap: 20px;
    align-items: center;
  }
  
  .avatar-section {
    margin-bottom: 0;
  }
  
  .level-info-section {
    width: 100%;
  }
  
  /* 确保等级和称号在小屏幕上也能正常显示 */
  .level-header {
    gap: 8px;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .level-badge {
    padding: 4px 10px;
    font-size: 13px;
  }
  
  .level-title {
    font-size: 15px;
  }
}

@media (max-width: 480px) {
  .profile-header {
    padding: 25px 15px;
  }
  
  .profile-content {
    padding: 25px 15px;
  }
  
  .profile-title {
    font-size: 24px;
  }
  
  .user-avatar {
    width: 80px !important;
    height: 80px !important;
  }
  
  .info-card {
    padding: 15px;
  }
}
</style> 